<template>
    <div class="dice_wp" style="pointer-events: auto;">
        <div class="dice_wrap">
            <div class="diceGameInfo">
                <p class="typeName">{{ $t('m.sicbo.bet.bet[0]') }} <span @click="aCpt({explainShow: true})">?</span></p>
                <div class="gameBuy">
                    <div class="gameSelOut">
                        <div class="gameSel small" :class="betType=='small'?'selected':''"
                             @click="changeBetType('small')">
                            <div>{{ $t('m.sicbo.bet.type.small') }}</div>
                            <div>{{ num.small }}</div>
                        </div>
                    </div>
                    <div class="gameSelOut">
                        <div class="gameSel big" :class="betType=='big'?'selected':''" @click="changeBetType('big')">
                            <div>{{ $t('m.sicbo.bet.type.big') }}</div>
                            <div>{{ num.big }}</div>
                        </div>
                    </div>
                    <div class="gameSelOut">
                        <div class="gameSel" :class="betType=='same'?'selected':''" @click="changeBetType('same')">
                            <div>{{ $t('m.sicbo.bet.type.same') }}</div>
                            <div>{{ num.same }}</div>
                        </div>
                    </div>
                    <div class="gameSelOut">
                        <div class="gameSel small" :class="betType=='single'?'selected':''"
                             @click="changeBetType('single')">
                            <div>{{ $t('m.sicbo.bet.type.single') }}</div>
                            <div>{{ num.single }}</div>
                        </div>

                    </div>
                    <div class="gameSelOut">
                        <div class="gameSel small" :class="betType=='double'?'selected':''"
                             @click="changeBetType('double')">
                            <div>{{ $t('m.sicbo.bet.type.double') }}</div>
                            <div>{{ num.double }}</div>
                        </div>
                    </div>
                </div>
                <div style="clear: both;"></div>
            </div>
            <div class="diceBuyInfo">
                <div class="buyInfo numInfo">
                    <div class="buyInfoTitle">
                        <p class="title">{{ $t('m.sicbo.bet.bet[4]') }}</p>
                    </div>
                    <div class="setNum">
                        <img src="@/assets/img/remove.png" alt="" @click="add(-1)">
                        <input class="intoNum" type="number" name="intoNum" v-model="num[betType]"/>
                        <img src="@/assets/img/add-white.png" alt="" @click="add(1)">
                    </div>
                    <p class="info">{{ $t('m.sicbo.bet.bet[5]') }} {{ num[betType]}} ETSC</p>
                </div>
                <div class="buyInfo numInfo">
                    <div class="buyInfoTitle">
                        <p class="title">{{ $t('m.sicbo.bet.bet[6]') }}</p>
                    </div>
                    <div class="setNum">
                        <div class="setWin win1"><img src="@/assets/img/coin.png" alt=""></div>
                        <div class="setWin win2">
                            <template v-if="betType == 'same'">24.0</template>
                            <template v-else>2.00</template>
                        </div>
                        <div class="setWin win3"><img src="@/assets/img/close.png" alt="" style="width: 20px;"></div>
                    </div>
                    <p class="info">
                        <template v-if="betType == 'same'">
                            {{ $t('m.sicbo.bet.bet[7]') }} {{ price * num[betType] * 24}} ETSC
                        </template>
                        <template v-else>
                            {{ $t('m.sicbo.bet.bet[7]') }} {{ price * num[betType] * 2}} ETSC
                        </template>
                    </p>
                </div>
                <div style="clear: both;"></div>
            </div>
            <p class="dice_tips">{{ $t('m.sicbo.bet.bet[8]') }}</p>
            <div class="btn_wp" style="margin-top: 12px;">
                <div class="btn1 dicebtn" @click="betPre('bet')">
                    <span>{{ $t('m.sicbo.bet.bet[9]') }}</span>
                </div>
            </div>
            <div class="sicbo-balance" style="margin-top: 10px;">{{$t('m.efomo.biling.content.inputBox.text')[2]}}:&nbsp;
                {{ balance.ETSC | roundOff(2) }}
                ETSC
            </div>
        </div>
        <div class="record" v-show="list.length > 0">
            <p class="recordTitle">{{ $t('m.sicbo.bet.bet[10]') }}</p>
            <div>
                <table>
                    <thead>
                    <tr>
                        <th>{{ $t('m.sicbo.list.list[0]') }}</th>
                        <th>{{ $t('m.sicbo.list.list[1]') }}</th>
                        <th>{{ $t('m.sicbo.list.list[2]') }}</th>
                        <th>{{ $t('m.sicbo.list.list[3]') }}</th>
                    </tr>
                    </thead>
                    <tbody>
                    <!--eslint-disable-next-line-->
                    <tr v-for="(v,k) in list" :key="k" v-if="v.rid">
                        <td>
                            <div class="td1">Round#{{ v.rid }}</div>
                        </td>
                        <td>
                            <div class="td2">
                                <template v-if="v.bet_type == '0'">
                                    <div class="td2p1">{{ $t('m.sicbo.bet.type.small') }}</div>
                                </template>
                                <template v-if="v.bet_type == '1'">
                                    <div class="td2p1">{{ $t('m.sicbo.bet.type.big') }}</div>
                                </template>
                                <template v-if="v.bet_type == '2'">
                                    <div class="td2p1">{{ $t('m.sicbo.bet.type.same') }}</div>
                                </template>
                                <template v-if="v.bet_type == '3'">
                                    <div class="td2p1">{{ $t('m.sicbo.bet.type.single') }}</div>
                                </template>
                                <template v-if="v.bet_type == '4'">
                                    <div class="td2p1">{{ $t('m.sicbo.bet.type.double') }}</div>
                                </template>
                                <div class="td2p2">Bet {{ v.eth }}</div>
                            </div>
                        </td>
                        <td>
                            <div class="td3">
                                <div class="betRes1">
                                    <div :class="'dice dice_'+v.num1">
                                        <div v-for="(n,k) in v.num1" :key="k" :class="'dicePoint point_'+n"></div>
                                    </div>
                                    <div :class="'dice middle dice_'+v.num2">
                                        <div v-for="(n,k) in v.num2" :key="k" :class="'dicePoint point_'+n"></div>
                                    </div>
                                    <div :class="'dice dice_'+v.num3">
                                        <div v-for="(n,k) in v.num3" :key="k" :class="'dicePoint point_'+n"></div>
                                    </div>
                                    <div style="clear: both;"></div>
                                </div>
                                <div class="betRes2">
                                    <template v-if="!v.isWin">
                                        {{ $t('m.sicbo.list.list[5]') }}
                                    </template>
                                    <template v-else>
                                        {{ $t('m.sicbo.list.list[4]') }}
                                    </template>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="betNum" v-if="v.isWin && !v.isWithdraw" @click="betPre(v)">{{ $t('m.sicbo.list.list[6]') }}</span>
                            <span class="betNum" v-if="v.isWin && v.isWithdraw" style="color: #97989a;">{{ $t('m.sicbo.list.list[7]') }}</span>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>
<script>
    import "@/assets/css/bet.scss";
    import axios from 'axios';
    import {myAlert} from "@/assets/js/h5plus/nativeUI";
    import {withdraw, buy} from "@/assets/js/etherjs/sicbo";
    import {AESDecrypt} from '@/assets/js/utils/crypto'

    export default {
        name: 'sicbo_bet',
        created() {
            // 按下安卓返回键后，让页面不返回
        },
        mounted() {
            this.betList();
            this.aCpt({id: this._uid});
        },
        data() {
            return {
                request: {
                    pageNo: 1,
                    pageSize: 10,
                    address: "",
                    isEnd: false,
                },
                list: [],
                betType: 'small',
                price: 1,
                num: {
                    small: 0,
                    big: 0,
                    same: 0,
                    single: 0,
                    double: 0
                },
                max: 1000
            }
        },
        watch: {
            // 监听密码框-确认按钮
            prompt(v) {
                if (v.isConfirm) {
                    let pKey = AESDecrypt({
                        pwd: v.value,
                        msg: this.walletActive.pKey
                    });
                    if (pKey == '') {
                        myAlert({
                            msg: this.$t('m.wallet.manager.index.prompt[7]'),
                            button: this.$t('m.wallet.manager.index.prompt[4]')
                        });
                        return
                    }
                    this.aWalletDecode({
                        pKey: pKey
                    });
                    if (v.complete == 'bet') {
                        // computed计算到的变化，不及时？
                        this.bet();
                    } else {
                        // computed计算到的变化，不及时？
                        this.withdraw(v.complete);
                    }
                }
            }
        },
        methods: {
            init: function () {
                this.request.pageNo = 1;
                this.request.isEnd = false;
                this.list = [];
                return this.betList();
            },
            betList: function () {
                if (this.request.isEnd) return new Promise((resolve) => {
                    resolve(1);
                });
                // this.aLoading({show: true, tip: this.$t('m.wallet.transaction.list.prompt[7]')});
                this.request.address = this.walletActive.address;
                return axios.get('http://api.etscscan.com/client/sicbo/bet', {
                    params: this.request
                }).then((response) => {
                    if (response.data.error_code != 0) {
                        throw new Error("get list error");
                    }
                    let betList = response.data.data.list;
                    for (let i in betList) {
                        if (betList[i].res == null) {
                            continue
                        }
                        let num1 = Number(betList[i].res.substring(0, 1));
                        let num2 = Number(betList[i].res.substring(1, 2));
                        let num3 = Number(betList[i].res.substring(2, 3));
                        if (num1 == num2 && num1 == num3) {
                            betList[i].isWin = Number(betList[i].bet_type) == 2
                        } else {
                            betList[i].isWin = ((num1 + num2 + num3) > 10 && Number(betList[i].bet_type) == 1)
                                || ((num1 + num2 + num3) <= 10 && Number(betList[i].bet_type) == 0)
                                || (((num1 + num2 + num3) % 2) == 1 && Number(betList[i].bet_type) == 3)
                                || (((num1 + num2 + num3) % 2) == 0 && Number(betList[i].bet_type) == 4);
                        }

                        betList[i].num1 = num1;
                        betList[i].num2 = num2;
                        betList[i].num3 = num3;
                        betList[i].eth = betList[i].eth / 10 ** 9;
                        let withdrawAll = localStorage.getItem("withdrawAll") ? localStorage.getItem("withdrawAll") : "";
                        betList[i].isWithdraw = withdrawAll.indexOf("x" + betList[i].rid + this.walletActive.address + "x") > -1;
                    }

                    this.list = this.list.concat(betList);
                    if (betList.length < this.request.pageSize) this.request.isEnd = true;
                    // this.aLoading({show: false, tip: this.$t('m.wallet.transaction.list.prompt[7]')});
                }).catch((error) => {
                    // this.aLoading({show: false,});
                    myAlert({
                        msg: this.$t('m.wallet.transaction.list.prompt[8]'),
                        button: this.$t('m.wallet.transaction.list.prompt[9]')
                    });
                    console.log(error);
                });
            },
            getMore: function () {
                this.request.pageNo++;
                return this.betList();
            },
            betPre: function (v) {
                if (this.walletDecode.pKey == "") {
                    this.aPrompt({
                        show: true,
                        title: this.$t('m.my.identity.prompt[7]'),
                        cancel: this.$t('m.my.identity.prompt[8]'),
                        confirm: this.$t('m.my.identity.prompt[6]'),
                        type: "password",
                        placeholder: this.$t('m.my.identity.prompt[7]'),
                        complete: v
                    })
                } else {
                    if (v == 'bet') {
                        this.bet();
                    } else {
                        this.withdraw(v)
                    }
                }
            },

            bet: async function () {
                /* eslint-disable */
                let allNum = 0, eth = [];
                // 单注最大投注1000
                let rObj = localStorage.getItem("rid_num") ?
                    JSON.parse(localStorage.getItem("rid_num")) : {
                        small: 0,
                        big: 0,
                        same: 0,
                        single: 0,
                        double: 0,
                        rid: Number(this.round.id.toString())
                    };
                if (rObj.rid != Number(this.round.id.toString())) {
                    rObj = {
                        small: 0,
                        big: 0,
                        same: 0,
                        single: 0,
                        double: 0,
                        rid: Number(this.round.id.toString())
                    }
                }
                for (let i in this.num) {
                    if ((parseInt(rObj[i]) + parseInt(this.num[i])) > this.max) {
                        myAlert({
                            msg: this.$t('m.wallet.transaction.maxError'),
                            button: this.$t('m.wallet.transaction.list.prompt[9]')
                        });
                        return;
                    } else {
                        rObj[i] = parseInt(rObj[i]) + parseInt(this.num[i]);
                    }
                    allNum += parseInt(this.num[i])
                }
                localStorage.setItem("rid_num", JSON.stringify(rObj));

                eth[0] = parseInt(this.num.small) * this.price;
                eth[1] = parseInt(this.num.big) * this.price;
                eth[2] = parseInt(this.num.same) * this.price;
                eth[3] = parseInt(this.num.single) * this.price;
                eth[4] = parseInt(this.num.double) * this.price;

                if (allNum == 0) {
                    myAlert({
                        msg: this.$t('m.sicbo.bet.alert.noNum'),
                        button: this.$t('m.wallet.transaction.list.prompt[9]')
                    });
                    return;
                }
                if (parseFloat(this.balance.ETSC) < (this.price * allNum + 0.02)) {
                    this.plusDiff(() => {
                        plus.nativeUI.toast(this.$t('m.sicbo.bet.error[1]'), {verticalAlign: 'center'});
                    });
                    return;
                }
                this.plusDiff(() => {
                    plus.nativeUI.toast(this.$t('m.sicbo.bet.load[0]'), {verticalAlign: 'center'});
                });
                let res = await buy({
                    privateKey: this.walletDecode.pKey,
                    value: this.price * allNum,
                    eth: eth
                });
                if (res == 0) {
                    this.plusDiff(() => {
                        plus.nativeUI.toast(this.$t('m.sicbo.bet.error[0]'), {verticalAlign: 'center'});
                    });
                } else {
                    // 更新余额
                    this.$parent.synBalanceOnce();
                    this.plusDiff(() => {
                        plus.nativeUI.toast(this.$t('m.sicbo.bet.success[0]'), {verticalAlign: 'center'});
                    });
                }
            },

            withdraw: async function (v) {
                let rID = v.rid;

                // 解析私钥
                this.plusDiff(() => {
                    plus.nativeUI.toast(this.$t('m.sicbo.bet.load[1]'), {verticalAlign: 'center'});
                });
                let res = await withdraw({
                    privateKey: this.walletDecode.pKey,
                    rid: rID
                });
                console.log(res);
                if (res == 0) {
                    this.plusDiff(() => {
                        plus.nativeUI.toast(this.$t('m.sicbo.bet.error[2]'), {verticalAlign: 'center'});
                    });
                } else {
                    // 更新余额
                    this.$parent.synBalanceOnce();
                    this.plusDiff(() => {
                        plus.nativeUI.toast(this.$t('m.sicbo.bet.success[1]'), {verticalAlign: 'center'});
                    });
                    // 已提现
                    let withdrawAll = localStorage.getItem("withdrawAll") ? localStorage.getItem("withdrawAll") : "";
                    if (withdrawAll.indexOf("x" + rID + this.walletActive.address + "x") < 0) {
                        withdrawAll = withdrawAll + ",x" + rID + this.walletActive.address + "x";
                        localStorage.setItem("withdrawAll", withdrawAll);
                    }
                    v.isWithdraw = true;
                }

            },
            add: function (v) {
                if ((Number(this.num[this.betType]) + v) >= 0) this.num[this.betType] = Number(this.num[this.betType]) + v;
            },
            changeBetType: function (v) {
                document.querySelector(".intoNum").blur();
                this.betType = v;
            },
        },

    }
</script>
<style scoped>

</style>